package com.ca.ridersclubapplication;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.ca.ridersclubapplication.data.DataHandler;
import com.ca.ridersclubapplication.data.entity.BooleanEntity;
import com.ca.ridersclubapplication.data.entity.Handleable;
import com.ca.ridersclubapplication.data.entity.ListEntity;
import com.ca.ridersclubapplication.data.entity.LongEntity;
import com.ca.ridersclubapplication.data.entity.StringEntity;
import com.ca.ridersclubapplication.request.AfterExecutor;
import com.ca.ridersclubapplication.request.ClubRequester;
import com.ca.ridersclubapplication.request.FileRequester;
import com.ca.ridersclubapplication.request.PaperRequester;
import com.ca.ridersclubapplication.request.dto.ClubDto;
import com.ca.ridersclubapplication.request.dto.Result;
import com.ca.ridersclubapplication.util.KeyBoardUtil;
import com.ca.ridersclubapplication.util.PaperUtils;
import com.ca.ridersclubapplication.view.CallbackView;
import com.ca.ridersclubapplication.view.bar.MiniClubTitleBar;
import com.ca.ridersclubapplication.view.input.PaperEditInput;
import com.dylanc.activityresult.launcher.GetMultipleContentsLauncher;
import com.ea.ui.core.basic.EATextField;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class EditPaperActivity extends ImmersiveActivity {

    private Long clubId;

    //  顶部交互控件
    private ImageView backView;
    private Button submitButton;

    //  车友圈标题栏
    private MiniClubTitleBar clubTitleBar;

    //  标题输入控件
    private EATextField titleTF;

    //  内容输入控件
    private final List<PaperEditInput> inputList = new ArrayList<>();
    private PaperEditInput appearanceInput;
    private PaperEditInput performanceInput;
    private PaperEditInput energyInput;
    private PaperEditInput moreInput;

    private String title;
    private String appearance;
    private String performance;
    private String energy;
    private String more;


    //  退出编辑对话框
    private Dialog dialog;
    private TextView cancelButton;
    private TextView sureButton;

    //  放入数据处理器中的回调视图
    private CallbackView callbackView;

    //  用于打开相册的启动器
    private GetMultipleContentsLauncher launcher;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_paper);

        initData();

        initView();

        initListener();

        loadData();
    }


    private void initData() {
        Intent intent = getIntent();
        clubId = intent.getLongExtra("clubId", 0L);
        if (clubId == 0) {
            Toast.makeText(this, "操作失败", Toast.LENGTH_SHORT).show();
            finishAfterTransition();
        }
    }


    private void initView() {

        //  顶部交互控件
        backView = findViewById(R.id.iv_back);
        submitButton = findViewById(R.id.btn_post);

        //  车友圈标题栏
        clubTitleBar = findViewById(R.id.bar_clubTitle);

        //  内容输入控件
        titleTF = findViewById(R.id.tf_title);
        appearanceInput = findViewById(R.id.input_appearance);
        performanceInput = findViewById(R.id.input_performance);
        energyInput = findViewById(R.id.input_energy);
        moreInput = findViewById(R.id.input_more);

        inputList.add(appearanceInput);
        inputList.add(performanceInput);
        inputList.add(energyInput);
        inputList.add(moreInput);

        //  退出编辑对话框
        @SuppressLint("InflateParams")
        View view = LayoutInflater.from(this).inflate(R.layout.paper_edit_close_dialog_layout, null);
        dialog = new Dialog(this);
        dialog.setContentView(view);
        cancelButton = view.findViewById(R.id.btn_cancel);
        sureButton = view.findViewById(R.id.btn_sure);

        //  用于打开相册的启动器
        launcher = new GetMultipleContentsLauncher(this);
    }


    private void initListener() {

        //  返回对话框按钮点击事件（取消退出、确认退出）
        cancelButton.setOnClickListener(v -> {
            dialog.dismiss();
        });
        sureButton.setOnClickListener(v -> {
            dialog.dismiss();
            finishAfterTransition();
        });

        //  返回按钮点击事件
        backView.setOnClickListener(v -> {
            dialog.show();
        });

        //  禁用车友会点击
        clubTitleBar.setEnabled(false);

        //  添加图片点击事件
        for (int i = 0; i < inputList.size(); i++) {
            PaperEditInput input = inputList.get(i);
            input.addImageButton.setOnClickListener(v -> {
                //  打开相册
                 launcher.launchForImage(
                         uriList -> {
                             for (Uri uri : uriList) {
                                 // 根据系统版本的不同，解析Uri（获取可用的路径）
                                 String path;
                                 if (Build.VERSION.SDK_INT > 21) {
                                     // 4.4及以上系统使用这个方法处理图片
                                     path = handleImageOnKitKat(uri);
                                 } else {
                                     // 4.4以下系统使用这个方法处理图片
                                     path = getImagePath(uri, null);
                                 }
                                 // 添加图片
                                 input.addImage(path);
                             }
                         },
                         settingsLauncher -> {
                             // 用户始终拒绝了权限请求
                             Toast.makeText(this, "请允许访问相册", Toast.LENGTH_SHORT).show();
                             settingsLauncher.launch();
                         },
                         () -> {
                             // 用户拒绝了一次权限请求，提示用户
                             Toast.makeText(this, "请允许访问相册", Toast.LENGTH_SHORT).show();
                         }
                 );
            });
        }

        //  提交按钮点击事件
        submitButton.setOnClickListener(v -> {

            //  按钮设为不可用，防止多次提交
            submitButton.setEnabled(false);

            //  输入内容校验
            if (checkInput()) {

                Log.e("上传文章", "内容校验通过");

                //  需要提交的图片数量
                final long imageCount = appearanceInput.getPathList().size()
                        + performanceInput.getPathList().size()
                        + energyInput.getPathList().size()
                        + moreInput.getPathList().size();
                Log.e("上传文章", "需要提交的图片数量：" + imageCount);

                if (imageCount == 0) {
                    //  无图内容直接上产文章即可
                    //  内容封装
                    String content = PaperUtils.createContent(
                            DataHandler.getToken(this).getId(),
                            appearance, appearanceInput.getPathList(),
                            performance, performanceInput.getPathList(),
                            energy, energyInput.getPathList(),
                            more, moreInput.getPathList());
                    PaperRequester.addPaper(this, title, content, clubId, new AfterExecutor<String>() {
                        @Override
                        public void execute(Result<String> result) {
                            if (result.isSuccess()) {
                                Toast.makeText(EditPaperActivity.this, "发布成功", Toast.LENGTH_SHORT).show();
                                //  发布成功后，向数据处理器中放入，触发ClubActivity重新请求文章数据
                                DataHandler.putData(new BooleanEntity("AddPaper", true));

                                //  存入数据，触发回调
                                DataHandler.putData(new LongEntity("PaperCount:" + DataHandler.getToken(EditPaperActivity.this).getId(), 1L));

                                //  关闭编辑文章Activity
                                EditPaperActivity.this.finishAfterTransition();
                            }
                        }
                    });
                }
                //  由于上传图片完成后才能够提交文章数据，因此需要放入数据处理器中等待回调
                callbackView = new CallbackView() {
                    @Override
                    public void update() {
                        Handleable data = DataHandler.getData("UploadImageSize");
                        if (data instanceof LongEntity) {
                            Long count = ((LongEntity) data).getValue();
                            Log.e("上传文章", "当前已上传图片：" + count);
                            if (!count.equals(imageCount)) {
                                return;
                            }

                            //  当上传完成的图片数量与总数量一致时，开始上传文章数据
                            //  获取上传头像后返回的数据

                            //  外观图片列表
                            Handleable ainul = DataHandler.getData("NetworkUrlList:Appearance");
                            List<String> appearanceUUIDList = new ArrayList<>();
                            if (ainul instanceof ListEntity) {
                                ListEntity<?> le = (ListEntity<?>) ainul;
                                for (Handleable h : le.getList()) {
                                    if (h instanceof StringEntity) {
                                        String url = ((StringEntity) h).getValue();
                                        appearanceUUIDList.add(url);
                                    }
                                }
                            }

                            //  性能图片列表
                            Handleable pinul = DataHandler.getData("NetworkUrlList:Performance");
                            List<String> performanceUrlList = new ArrayList<>();
                            if (pinul instanceof ListEntity) {
                                ListEntity<?> le = (ListEntity<?>) pinul;
                                for (Handleable h : le.getList()) {
                                    if (h instanceof StringEntity) {
                                        String url = ((StringEntity) h).getValue();
                                        performanceUrlList.add(url);
                                    }
                                }
                            }

                            //  能耗图片列表
                            Handleable einul = DataHandler.getData("NetworkUrlList:Energy");
                            List<String> energyUUIDList = new ArrayList<>();
                            if (einul instanceof ListEntity) {
                                ListEntity<?> le = (ListEntity<?>) einul;
                                for (Handleable h : le.getList()) {
                                    if (h instanceof StringEntity) {
                                        String url = ((StringEntity) h).getValue();
                                        energyUUIDList.add(url);
                                    }
                                }
                            }

                            //  其他图片列表
                            Handleable minul = DataHandler.getData("NetworkUrlList:More");
                            List<String> moreUUIDList = new ArrayList<>();
                            if (minul instanceof ListEntity) {
                                ListEntity<?> le = (ListEntity<?>) minul;
                                for (Handleable h : le.getList()) {
                                    if (h instanceof StringEntity) {
                                        String url = ((StringEntity) h).getValue();
                                        moreUUIDList.add(url);
                                    }
                                }
                            }

                            //  内容封装
                            String content = PaperUtils.createContent(
                                    DataHandler.getToken(EditPaperActivity.this).getId(),
                                    appearance, appearanceUUIDList,
                                    performance, performanceUrlList,
                                    energy, energyUUIDList,
                                    more, moreUUIDList);

                            //  发起请求
                            PaperRequester.addPaper(EditPaperActivity.this, title, content, clubId, new AfterExecutor<String>() {
                                @Override
                                public void execute(Result<String> result) {
                                    if (result.isSuccess()) {
                                        Toast.makeText(EditPaperActivity.this, "发布成功", Toast.LENGTH_SHORT).show();
                                        //  发布成功后，向数据处理器中放入，触发ClubActivity重新请求文章数据
                                        DataHandler.putData(new BooleanEntity("AddPaper", true));

                                        //  将数据管理器中上传头像的数量置零
                                        DataHandler.putData(new LongEntity("UploadImageSize", 0L));

                                        //  关闭编辑文章Activity
                                        EditPaperActivity.this.finishAfterTransition();
                                    }
                                }
                            });
                        }
                    }
                };
                DataHandler.putView("UploadImageSize", callbackView);

                //  上传图片
                FileRequester.uploadPaperImages(this, "NetworkUrlList:Appearance", appearanceInput.getPathList(), null);
                FileRequester.uploadPaperImages(this, "NetworkUrlList:Performance", performanceInput.getPathList(), null);
                FileRequester.uploadPaperImages(this, "NetworkUrlList:Energy", energyInput.getPathList(), null);
                FileRequester.uploadPaperImages(this, "NetworkUrlList:More",  moreInput.getPathList(), null);
            }
        });
    }


    private void loadData() {
        getClub();
    }


    private void getClub() {
        ClubRequester.getClubById(this, clubId, new AfterExecutor<ClubDto>() {
            @Override
            public void execute(Result<ClubDto> result) {
                ClubDto dto = result.getData();
                if (result.isSuccess() && dto != null) {
                    //  请求成功，设置车友圈标题栏数据
                    clubTitleBar.setImageUrl(FileRequester.CLUB_IMAGE_1_1_BASE_URL + dto.getId());
                    clubTitleBar.setName(dto.getName());
                    clubTitleBar.setFollowCount(dto.getFansCount());
                }
            }
        });
    }

    @Override
    public void onBackPressed() {
        dialog.show();
    }


    /**
     * 检查输入内容是否合法
     */
    private boolean checkInput() {

        title = Objects.requireNonNull(titleTF.getText()).toString();
        if (title.trim().isEmpty()) {
            Toast.makeText(this, "请输入文章标题", Toast.LENGTH_SHORT).show();
            KeyBoardUtil.showSoftInput(this, titleTF);
            submitButton.setEnabled(true);
            return false;
        }

        appearance = Objects.requireNonNull(appearanceInput.inputView.getText()).toString();
        if (appearance.trim().isEmpty()) {
            Toast.makeText(this, "请输入外观相关内容", Toast.LENGTH_SHORT).show();
            KeyBoardUtil.showSoftInput(this, appearanceInput.inputView);
            submitButton.setEnabled(true);
            submitButton.setEnabled(true);
            return false;
        }

        performance = Objects.requireNonNull(performanceInput.inputView.getText()).toString();
        if (performance.trim().isEmpty()) {
            Toast.makeText(this, "请输入性能相关内容", Toast.LENGTH_SHORT).show();
            KeyBoardUtil.showSoftInput(this, performanceInput.inputView);
            submitButton.setEnabled(true);
            return false;
        }

        energy = Objects.requireNonNull(energyInput.inputView.getText()).toString();
        if (energy.trim().isEmpty()) {
            Toast.makeText(this, "请输入能耗相关内容", Toast.LENGTH_SHORT).show();
            KeyBoardUtil.showSoftInput(this, energyInput.inputView);
            submitButton.setEnabled(true);
            return false;
        }

        more = Objects.requireNonNull(moreInput.inputView.getText()).toString();
        if (more.trim().isEmpty()) {
            more = "无";
        }

        return true;
    }


    /**
     * android 4.4以上的处理方式
     */
    private String handleImageOnKitKat(Uri uri) {
        String imagePath = null;
        if (DocumentsContract.isDocumentUri(this, uri)) {
            // 如果是document类型的Uri，则通过document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];
                // 解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content: //downloads/public_downloads"), Long.parseLong(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // 如果是content类型的Uri，则使用普通方式处理
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            // 如果是file类型的Uri，直接获取图片路径即可
            imagePath = uri.getPath();
        }
        return imagePath;
    }

    //  获取路径
    private String getImagePath(Uri uri, String selection) {
        String path = null;
        // 通过Uri和selection来获取真实的图片路径
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            int index = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
            if (index == -1) {
                return null;
            }
            path = cursor.getString(index);
            cursor.close();
        }
        return path;
    }
}